package path;

import java.io.File;
import java.net.URISyntaxException;
import java.net.URL;

import conf.Configure;


public class PathManager {
	public static final String M5Craft_HIDDEN_FOLDER_NAME = ".M5Craft";

	private static final String LOG_DIR = "logs";

	private static PathManager instance;
	private File installPath;
	private File homePath;
	private File logPath;

	private PathManager() {
		try {
			URL path = PathManager.class.getProtectionDomain().getCodeSource().getLocation();
			File codeLocation = new File(path.toURI());
			if (codeLocation.isFile()) {
				installPath = codeLocation.getParentFile();
			}
		} catch (URISyntaxException e) {
			// Can't use logger, because logger not set up when PathManager is used.
			System.out.println("Failed to convert to uri");
		}
		if (installPath == null) {
			installPath = new File("").getAbsoluteFile();
		}
		homePath = installPath;
	}

	public static PathManager getInstance() {
		if (instance == null) {
			instance = new PathManager();
		}
		return instance;
	}

	public void buildPaths(){
		this.buildPaths(null);
	}
	
	public void buildPaths(File homePath){
		String configureHomePath = Configure.getHomeDir();
		if (homePath == null && configureHomePath != null) {
			homePath = new File(configureHomePath);
		}

		if (homePath != null) {
			useOverrideHomePath(homePath);
		} else {
			useDefaultHomePath();
		}
	}
	
	public void useDefaultHomePath() {
		homePath = new File(System.getProperty("user.home"), M5Craft_HIDDEN_FOLDER_NAME);
		updateDirs();
	}

	public void useOverrideHomePath(File rootPath) {
		this.homePath = rootPath;
		updateDirs();
	}

	private void updateDirs() {
		homePath.mkdirs();
		logPath = new File(homePath, LOG_DIR);
		logPath.mkdirs();
	}

	public File getInstallPath() {
		return installPath;
	}

	public void setInstallPath(File installPath) {
		this.installPath = installPath;
	}

	public File getHomePath() {
		return homePath;
	}

	public void setHomePath(File homePath) {
		this.homePath = homePath;
	}

	public File getLogPath() {
		return logPath;
	}

	public void setLogPath(File logPath) {
		this.logPath = logPath;
	}
}
